<?php

namespace App\Console\Commands\OpenShop;


use AlibabaCloud\Kms\Kms;
use App\Models\FeishuCallingCard\FeishuCallingCard;
use App\Models\Kms\User\KmsUser;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationManageModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationExamineLogModel;
use App\Remote\Rms\RmsUserRemote;
use Guanguans\Notify\Factory;
use Illuminate\Console\Command;

class OpenShopSiteLocationExamineCycle extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'open_shop:site_location_examine_cycle {--cycle=daily}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '周期性推送选址审核记录,
    {--cycle= : 周期性类型 daily:日, weekly:周, monthly:月}
    ';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    public const CYCLE_TYPE_DAILY   = 'daily';
    public const CYCLE_TYPE_WEEKLY  = 'weekly';
    public const CYCLE_TYPE_MONTHLY = 'monthly';
    public const BLACK_LIST_USERID  = [
        139, // 风雪
        51, // 九月
        13, // 胡迪
        14, // 山治
        16, // 夏目
        1195, // 栗子 不知道要不要
        8410, // 阿贡
    ];

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $cycleType = $this->option('cycle');
        switch ($cycleType) {
            case 'custom':
                $startAtDate        = '2022-11-0';
                $startAtTimestamp   = strtotime($startAtDate);
                $endAtDate          = '2022-11-18';
                $endAtDateTimestamp = strtotime($endAtDate);
                $secondTitle        = '';

                $titleDate = "7月-选址审核 (" . date('Y-m-d', $startAtTimestamp) . ' - ' . date('Y-m-d',
                        $endAtDateTimestamp) . ')';
                break;
            case self::CYCLE_TYPE_WEEKLY:
                $startAtDate        = date('Y-m-d H:i:s',
                    mktime(0, 0, 0, date('m'), date('d') - date('w') + 1 - 7, date('Y')));
                $startAtTimestamp   = strtotime($startAtDate);
                $endAtDate          = date('Y-m-d H:i:s',
                    mktime(23, 59, 59, date('m'), date('d') - date('w') + 7 - 7, date('Y')));
                $endAtDateTimestamp = strtotime($endAtDate);
                $secondTitle        = '上周';

                $titleDate = "上周选址审核 (" . date('Y-m-d', $startAtTimestamp) . ' - ' . date('Y-m-d',
                        $endAtDateTimestamp) . ')';
                break;
            case self::CYCLE_TYPE_MONTHLY:
                $startAtDate        = date("Y-m-d H:i:s", mktime(0, 0, 0, date("m") - 1, 1, date("Y")));
                $startAtTimestamp   = strtotime($startAtDate);
                $endAtDate          = date("Y-m-d H:i:s", mktime(23, 59, 59, date("m"), 0, date("Y")));
                $endAtDateTimestamp = strtotime($endAtDate);
                $secondTitle        = '上月';

                $titleDate = "上月选址审核 (" . date('Y-m-d', $startAtTimestamp) . ' - ' . date('Y-m-d',
                        $endAtDateTimestamp) . ')';
                break;
            default:
            case self::CYCLE_TYPE_DAILY:
                $startAtDate = date('Y-m-d 00:00:00');
//                $startAtDate        = '2022-08-07';
                $startAtTimestamp   = strtotime($startAtDate);
                $endAtDateTimestamp = $startAtTimestamp + 86399;
                $endAtDate          = date('Y-m-d H:i:s', $endAtDateTimestamp);
                $secondTitle        = '今日';
                $titleDate          = "今日选址审核 (" . date('Y-m-d', $startAtTimestamp) . ')';
                break;

        }

        $baseQuery = OpenShopSiteLocationExamineLogModel::query()
                                                        ->where('createdAt', '>', $startAtTimestamp)
                                                        ->where('createdAt', '<', $endAtDateTimestamp)
                                                        ->whereIn('position', [
                                                            OpenShopSiteLocationExamineLogModel::POSITION_PROVINCE_EXAMINE,
                                                            OpenShopSiteLocationExamineLogModel::POSITION_CHARGE_EXAMINE,
                                                            OpenShopSiteLocationExamineLogModel::POSITION_GENERAL_EXAMINE,
                                                        ])
                                                        ->with('siteLocationRel')
                                                        ->where('source', 0);

        $countAll = (clone $baseQuery)->count();

        if (0 == $countAll) {
            return 0;
        }

        $userList = [];

        $countAll   = 0;
        $countAllow = 0;
        $countDeny  = 0;

        (clone $baseQuery)
            ->get()
            ->each(function ($value) use (&$userList, &$countAll, &$countAllow, &$countDeny) {

                if (empty($value->siteLocationRel)) {
                    return;
                }

                if (in_array($value->siteLocationRel->developConsultantId, self::BLACK_LIST_USERID)) {
                    return;
                }

                if (empty($userList[$value->siteLocationRel->developConsultantId])) {
                    if ($value->siteLocationRel->developConsultantId == 0) {
//                        dd($value->toArray());
                    }
                    $userList[$value->siteLocationRel->developConsultantId] = [
                        'userId'     => $value->siteLocationRel->developConsultantId,
                        'countAll'   => 0,
                        'countAllow' => 0,
                        'countDeny'  => 0
                    ];
                }


                // 通过
                if ($value->status == OpenShopSiteLocationExamineLogModel::STATUS_OK) {
                    $userList[$value->siteLocationRel->developConsultantId]['countAllow']++;
                    $countAllow++;
                } else {
                    $userList[$value->siteLocationRel->developConsultantId]['countDeny']++;
                    $countDeny++;
                }

                $userList[$value->siteLocationRel->developConsultantId]['countAll']++;
                $countAll++;
            });

        $userInfoList = self::getDevelopmentGroup(array_keys($userList));
        $userInfoList = array_column($userInfoList, null, 'rmsUserId');

        // 添加战区分组
        foreach ($userList as $userId => $user) {
            if (!isset($userInfoList[$userId])) {
                unset($userList[$userId]);
                continue;
            }
            $userList[$userId]['feishuUserId'] = $userInfoList[$userId]['feishuUserId'];
            $userList[$userId]['regionGroup']  = $userInfoList[$userId]['regionGroup'];
            $userList[$userId]['username']     = $userInfoList[$userId]['username'];
        }

        // 排序
        $userList = self::arraySort($userList, 'countAll', SORT_DESC);

        // 战区分组
        $regionGroupList = [];
        foreach ($userList as $value) {
            $regionGroupList[$value['regionGroup']][] = $value;
        }

        $element = [];
        foreach ($regionGroupList as $key => $regionUserList) {

            $newSignOrderTemp  = '';
            $companyCountAll   = 0;
            $companyCountAllow = 0;
            $companyCountDeny  = 0;
            foreach ($regionUserList as $regionUser) {
                $percent = bcdiv($regionUser['countAllow'], $regionUser['countAll'], 4) * 100;
                $newSignOrderTemp .= "<at id='{$regionUser['feishuUserId']}'></at>提审 {$regionUser['countAll']} 次, 通过 {$regionUser['countAllow']} 次, **被拒 {$regionUser['countDeny']} 次**, 通过率 {$percent}% " . PHP_EOL;
                $companyCountAllow += $regionUser['countAllow'];
                $companyCountDeny  += $regionUser['countDeny'];
                $companyCountAll   += $regionUser['countAll'];
            }

            // 战区总数据
            $percent      = bcdiv($companyCountAllow, $companyCountAll, 4) * 100;
            $companyTitle = "**{$key}**" . PHP_EOL;

            if ($cycleType != self::CYCLE_TYPE_DAILY) {
                $companyTitle = "**{$key}** 提审共 {$companyCountAll} 次, 通过 {$companyCountAllow} 次, **被拒 {$companyCountDeny} 次**, 通过率 {$percent}% " . PHP_EOL;
            }

            $tempElement = [
                [
                    "tag" => "hr",
                ],
                [
                    "tag"  => "div",
                    "text" => [
                        "content" => $companyTitle,
                        "tag"     => "lark_md"
                    ]
                ],
                [
                    "tag"  => "div",
                    "text" => [
                        "content" => $newSignOrderTemp,
                        "tag"     => "lark_md"
                    ]
                ],
            ];

            $element = array_merge($element, $tempElement);

        }

        $percent = bcdiv($countAllow, $countAll, 4) * 100;
        $card    = [
            'elements' => [
                [
                    "tag"     => "markdown",
                    "content" => "**{$secondTitle}共审核 {$countAll} 次, 通过 {$countAllow} 次, 拒审 {$countDeny} 次, 通过率 {$percent}%**"
                ],
            ],
            "header"   => [
                "title" => [
                    "content" => $titleDate,
                    "tag"     => "plain_text"
                ]
            ]
        ];

        $card['elements'] = array_merge($card['elements'], $element);

        $robot = self::getRobot();
        if (empty($robot)) {
            return 0;
        }
        Factory::feiShu()
               ->setToken($robot['urlToken'])
               ->setSecret($robot['secret'])
               ->setMessage(new \Guanguans\Notify\Messages\FeiShu\CardMessage($card))
               ->send();

    }


    private function getRobot()
    {
        if ('prod' == config('app.env')) {
            // 生产机器人
            return [
                'url'      => 'https://open.feishu.cn/open-apis/bot/v2/hook/5bb625a0-7d96-4117-a6c6-df346581e314',
                'urlToken' => '5bb625a0-7d96-4117-a6c6-df346581e314',
                'secret'   => 'IBmFS4Xr9yu0lOFgHkX9Vd'
            ];
        } else {
            return [];
            // 测试

            // return [
            //     // 测试群机器人
            //     'url'      => 'https://open.feishu.cn/open-apis/bot/v2/hook/541b19a5-99ca-4d6f-a556-e07155e5d6cc',
            //     'urlToken' => '541b19a5-99ca-4d6f-a556-e07155e5d6cc',
            //     'secret'   => 'g4gt6l3sXrp3E04GkYH1Yg',
            // ];
        }
    }

    private function getUserOpenIdTag($userName)
    {
        $userOpenIdMap = [
        ];

        if (!empty($userOpenIdMap[$userName])) {
            return "<at id=$userOpenIdMap[$userName]></at>";
        } else {
            return "<at id>$userName</at>";
        }
    }

    private function getFeishuUserInfo(array $userId = [])
    {
        $userList = RmsUserRemote::getRmsUserByIds($userId);

        $userList = array_column($userList, null, 'mobile');

        $mobileList = array_column($userList, 'mobile');


        $feishuUserList = FeishuCallingCard::query()
                                           ->whereIn('mobile', $mobileList)
                                           ->get()
                                           ->keyBy('mobile')
                                           ->toArray();

        foreach ($userList as &$value) {
            $value['feishuUserInfo'] = $feishuUserList[$value['mobile']] ?? [];

            // 判断是否是外部分公司
            if (strpos($value['username'], '外部') !== false) {
                $value['feishuUserInfo'] = [
                    'departmentName' => '外部分公司',
                    'realname'       => $value['username'],
                ];
            }

        }

        return $userList;
    }

    private function getCompanyList()
    {
        $list = OpenShopOrganizationManageModel::query()->get()->keyBy('name')->toArray();

        $list['商家增长中心'] = ['operationName' => '胖虎(赵文韬)'];

        return $list;

    }

    /**
     * 二维数组根据某个字段排序
     * @param array $array 要排序的数组
     * @param string $keys 要排序的键字段
     * @param string $sort 排序类型  SORT_ASC     SORT_DESC
     * @return array 排序后的数组
     */
    private function arraySort(array $array, string $keys, $sort = SORT_DESC): array
    {
        $keysValue = [];
        foreach ($array as $k => $v) {
            $keysValue[$k] = $v[$keys];
        }
        array_multisort($keysValue, $sort, $array);
        return $array;
    }

    /**
     * 获取用户战区分组列表
     * @param array $userIds
     * @return array
     */
    public static function getDevelopmentGroup(array $userIds = []): array
    {
        return KmsUser::query()
            ->when(count($userIds), function ($query) use ($userIds) {
                $query->whereIn('rmsUserId', $userIds);
            })
            ->where('rootDepartmentName', '分公司')
            // ->where('isFrozen', 0)
            // ->where('isResigned', KmsUser::IS_RESIGNED_OFF)
            // ->where('isExited', KmsUser::IS_EXITED_OFF)
            ->get()
            ->map(function (KmsUser $kmsUser) {

                $pattern = '/\/[^\/]*战区\//';

                if (preg_match($pattern, $kmsUser->groupParentDepartment, $matches)) {
                    $regionGroup = trim($matches[0], '/'); // 返回匹配的结果
                } else {
                    $regionGroup = '';
                }
                return [
                    'rmsUserId'    => $kmsUser->rmsUserId,
                    'username'     => $kmsUser->nickname . '(' . $kmsUser->name . ')',
                    'feishuUserId' => $kmsUser->userId,
                    'regionGroup'  => $regionGroup,
                ];
            })->toArray();
    }

}
